Epg.order = function(orderParam)
{
	Epg.tip("订购中,请勿关闭该页面 ^_^ ");
	var tipOrder = setTimeout(function(){
		android.startLutongOrder(orderParam);
		tipOrder && clearTimeout(tipOrder);
	}, 500);
}
//监听订购还回结果
Epg.onHttpOrderResponse = function(command, responseCode, lastOrderId, responseContent)
{
	if(command === 102)//订购
	{
		window.guoOrder.getRedirectUrl(command, responseCode == 0 ? "0" : "1", responseContent);
	}
}
//监听订购异常
Epg.onHttpOrderException = function(command, message)
{
	window.guoOrder.getRedirectUrl(command, "1", "订购异常: "+message);
};

/*
 * @param orderType = "";      //获取用户订购类型   year, quarter, month
@param feeType = "";     //订购对象   ggly_home, ggly_health
@param orderSourceType = "";    //获取对象类型  column, series
@param code = "";             //获取视频CODE
@param source = ""			// 从哪个页面进入订购 100011
@param ds = ""					// 优惠码
@param userCouponId = "";      //优惠券编号
 */

var GuoOrder = function(option)
{
	var settings = 
	{
		orderType: "year",
		feeType: "ggly_home",
		orderSourceType: "column",
		source: "ggly_home",
		code: "",
		ds: "",
		userCouponId: "",
		userProp: 0
	}
	for(var i in option)
	{
		if(option[i] !== undefined && option[i] !== "")
		{
			settings[i] = option[i];
		}
	}
	this.config = settings;
}

GuoOrder.prototype = {
	init: function(){
		var channel = Epg.cookie.get("CHANNEL_CODE");
		var appVersion = Epg.cookie.get("APP_VERSION");
		var postData = {"channel":channel,"appVersion":appVersion,"objectArr":this.config.feeType,"objectType":this.config.orderSourceType,"orderType":this.config.orderType};
		var _this = this;
		//查询用户要购买的商品
		Epg.postAPI("strategy/get-strategy-list", postData, function(data)
		{
			if(data && data.code == 0)
			{
				var strategyList = data.strategyList;			
				if(strategyList && strategyList.length != 0)
				{
					_this.feeId = data.strategyList[0].feeId;    //获取计费点ID			
					_this.strategyId = data.strategyList[0].id;      //获取计费策略ID
					//准备订购的订购类型
					var toOrderType = data.strategyList[0].orderType;
					if(channel == CONFIG.XIAOMI)
					{
						_this.checkOrderDeadline(_this.feeId,toOrderType);
					}else 
					{
						_this.getBossOrderId();
					}
				}
			}
		});
	},
	getRedirectUrl: function(command, ottOrderCode, ottOrderText){
		if(ottOrderCode == 0 && null != this.config.userCouponId && "" != this.config.userCouponId)
		{
			this.updateCoupon(this.config.userCouponId);
		}
		Show("order_dialog");
		G("order_dialog").style.top = G("order_dialog").offsetTop + G("wrapper").scrollTop + "px";      //这个是为了解决屏幕上滚时，弹窗不居中的问题
		order_exit_btn_id = Epg.btn.current.id;
		if(ottOrderCode == 0)
		{
			Epg.btn.get("order_baby").code = "order_baby";
			Epg.btn.get("order_ok").code = "order_ok";
			G("order_baby").innerHTML = "完善信息";
			G("order_ok").innerHTML = "不了,谢谢";
			
			S("order_ok_title");
			G("order_title").innerHTML = "亲，您订购果果乐园成功 ( ^_^ )";
			Epg.btn.set("order_ok");
		}else {
			G("order_baby").innerHTML = "再试一次";
			G("order_ok").innerHTML = "残忍拒绝";
			
			G("order_title").innerHTML = "亲，您订购果果乐园失败 ( ^_^ )";	
			Epg.btn.set("order_ok");
		}
		if((command  === 102) && (ottOrderCode === "1"))
		{
			Epg.cookie.set("userCouponId", this.config.userCouponId);   // 保存优惠券ID使其能监听用户在其他页面支付的时候能更新其状态
			Epg.cookie.set("bossOrderId", this.bossOrderId);			// 保存订单ID使其能监听用户在其他页面支付的时候能鉴权到
			Epg.cookie.set("listen_order_result_timer", new Date().getTime());
			Epg.isOrderResult();    //监听用户是否支付了订单
		}
		this.addOrder(ottOrderCode, ottOrderText);		
	},
	getBossOrderId: function(){
		var _this = this;
		var userId = Epg.cookie.get("userid");
		var channelId = Epg.cookie.get("CHANNEL_CODE");
		if(this.config.ds === null || this.config.ds === "")
		{
			this.config.ds = -1;
		}
		var postData = 
		{
			"userId":userId, "channelId":channelId,
			"pageType":this.config.orderSourceType,"pageName":this.config.source,
			"orderType":this.config.orderType, "productId":this.feeId, "ds":this.config.ds, "orderCount":"1"
		}
		if(channelId === "letv")
		{
			postData["payChannelType"] = "letv";
		}else if(channelId === "konka"){
			postData["payChannelType"] = "weixin";
		}else if(channelId === "migu_moblie"){
			postData["payChannelType"] = "weixin";
		}
		
		Epg.postAPI("boss/boss-order-info", postData, function(data)
		{
			if(data && data.code === 0)
			{
				var bossOrderInfo = data.bossOrderInfo;
				if("konka" === channelId || "migu_moblie" === channelId){
					//var jsonArray = JSON.parse(bossOrderInfo);
					var jsonArray = eval("(" +bossOrderInfo+ ")");
					
					jsonArray["userId"] = Epg.cookie.get("userid");
					jsonArray["orderType"] = _this.config.orderType;
					jsonArray["pageType"] = _this.config.orderSourceType;
					jsonArray["pageName"] = _this.config.source;
					jsonArray["productId"] = _this.feeId;
					jsonArray["ds"] = _this.config.ds;
					
					_this.bossOrderId = jsonArray.orderId;
					// _this.addOrderExtend(JSON.stringify(jsonArray));
					// Epg.order(JSON.stringify(jsonArray));
					var jStr = "";
					for(var item in jsonArray){
						jStr += '"'+item+'":"'+jsonArray[item]+'",';
					}
					jStr = "{" + jStr.slice(0, -1) + "}";
					_this.addOrderExtend(jStr);
					Epg.order(jStr);
				}else{
					//_this.bossOrderId = JSON.parse(bossOrderInfo).orderId;
					_this.bossOrderId = eval("(" +bossOrderInfo+ ")").orderId;
					_this.addOrderExtend(bossOrderInfo);
					Epg.order(bossOrderInfo);
				}
			}
		});
	},
	addOrderExtend: function(bossOrderInfo){
		var userId = Epg.cookie.get("userid");
		var postData = {"userId": userId, "bossOrderId": this.bossOrderId, "strategyId": this.strategyId, "bossOrderInfo": bossOrderInfo};
		if(this.config.userCouponId !== "")
		{
			postData["userCouponId"] = this.config.userCouponId;
		}
		Epg.postAPI("order-extend/add-order-extend", postData);
	},
	updateCoupon: function(userCouponId)
	{
		var postUserCouponData = {"userCouponId":userCouponId};
		Epg.postAPI("coupon/usercoupon/update", postUserCouponData);	
	},
	addOrder: function(ottOrderCode, ottOrderText)
	{
		var userId = Epg.cookie.get("userid");
		var role = Epg.cookie.get("role");
		var city = Epg.cookie.get("city");
		var ip = Epg.cookie.get("ip");
		var carrier = Epg.cookie.get("CARRIER");
		var appVersion = Epg.cookie.get("APP_VERSION", CONFIG.APP_VERSION);
		var platform = Epg.cookie.get("CHANNEL_CODE", CONFIG.PLATFORM);
		var entry = Epg.cookie.get("entry", "");
		var version = Epg.cookie.get("VERSION", CONFIG.VERSION);
		var apkVersion = Epg.cookie.get("APK_VERSION", CONFIG.APK_VERSION);
		this.config.userProp += 1;
		
		var postData = 
		{
			"userid": userId, "role": role, "orderType": this.config.orderType,
			"source": this.config.source, "sourceType": this.config.orderSourceType,
			"city": city, "carrier": carrier, "feeType": this.config.feeType, 
			"appVersion": appVersion, "platform": platform,
			"code": this.config.code, "version": version, "apkVersion": apkVersion, "userProp":this.config.userProp
		}
		if(0 == ottOrderCode)
		{
			postData["entry"] = entry;
			postData["bossOrderId"] = this.bossOrderId;
			Epg.postAPI("order/add-order-info", postData);
		}else {
			postData["description"] = ottOrderText;
			Epg.postAPI("order/add-failed", postData);
		}
	},
	//检查是否过了订购期限,针对小米渠道
	checkOrderDeadline: function(feedId,toOrderType)
	{
		var _this = this;
		var postData = {"productCode": "ggly", "userId":Epg.cookie.get("userid")};
		Epg.postAPI('boss/unexpired-feepoint-list', postData, function(data)
		{
			console.log(data);
			if(data && data.code == 0)
			{
				var html = '';
				var list = data.feepointList;
				//顾虑相同feeId的订购数据
				var orderDataArr=new Array(list.length)
				var j = 0;
				for(var i = 0;i<list.length;i++)
				{
					var obj = list[i];
					if(feedId == obj.code || 'ggly' == obj.code)
					{	
						orderDataArr[j++] = obj;
					}
				}
				if(orderDataArr.length==0){
					_this.getBossOrderId();
				}else if(orderDataArr[0].code == 'ggly' || feedId == orderDataArr[0].code){
				    var  aDate,  expiredTimestamp,  currentTimestamp;
				    aDate  =  orderDataArr[0].expiredDate.split("-")  ;
				    expiredTimestamp  =  new  Date(aDate[1]  +  '-'  +  aDate[2].substring(0,2)  +  '-'  +  aDate[0]).getTime() ;   //转换为12-18-2002格式  
					var currentTimestamp =(new Date()).getTime();
				    var useDays  =  parseInt(Math.abs(expiredTimestamp  -  currentTimestamp)  /  1000  /  60  /  60  /24)  ;  //把相差的毫秒数转换为天数 
				    //天数与能否订购类型的关系
				    var orderTypeArr = {"month":336,"quarter":276,"year":29};
				    
				    if(useDays <= orderTypeArr[toOrderType])
			    	{
				    	_this.getBossOrderId();
			    	}
				    else
		    		{
			    		Epg.tip("您已经达到了最长订购期限。");
		    		}
				}
				else
				{
					Epg.tip("订购异常，请扫描二维码，关注公众号，联系我们");
				}
			}
			else
			{
				Epg.tip('系统繁忙，请求数据失败！');
			}
		});
	}
};
